﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Xml.Linq;
using AzureReader.BLL;
using WindowsLive;

namespace AzureReader.Web
{
    public partial class _Default : System.Web.UI.Page
    {
        const string LoginCookie = "webauthtoken";

        
        static WindowsLiveLogin wll= new WindowsLiveLogin(true);

        protected static string AppId = wll.AppId;
        protected string UserId;

        protected void Page_Load(object sender, EventArgs e)
        {
            
     
            HttpRequest req = HttpContext.Current.Request;
            HttpCookie loginCookie = req.Cookies[LoginCookie];

            if (loginCookie != null)
            {
                string token = loginCookie.Value;

                if (!string.IsNullOrEmpty(token))
                {
                    WindowsLiveLogin.User user = wll.ProcessToken(token);
                    
                    if (user != null)
                    {
                        UserId = user.Id;
                         
                    }
                }
            }

            if(!IsPostBack)
                InitControls();
        }
        void InitControls()
        {
            if (string.IsNullOrEmpty(UserId))
            {
                pnlControls.Visible = false;
                return;
            }
          
                vwSubscription[] subs = FeedSubscriptionsManager.GetUserSubscriptions(UserId);

           
          lstSubs.DataSource = subs;
          lstSubs.DataBind();
            
        }
        protected void btnAdd_Click(object sender, EventArgs e)
        {
            FeedSubscriptionsManager.AddNewSubscription(UserId, txtSubscription.Text);
            Response.Redirect("Default.aspx");
        }
        protected void lnkFeed_Click(object sender, EventArgs args)
        {
            try
            {
               
                grdItems.DataSource =FeedSubscriptionsManager.GetFeedItems( (sender as LinkButton).CommandArgument);
                grdItems.DataBind();
            }
            catch (Exception ex)
            {
                System.Diagnostics.Trace.TraceError(ex.Message);

            }


        }
        protected string GetFeedCaption(vwSubscription sub)
        { 
            string text="";
            if (string.IsNullOrEmpty(sub.FeedName))
                text = sub.FeedUrl;
            else
                text = sub.FeedName;

            return text;
            //string[] unread = sub.GetUnreadItemsUrls();
            //if (unread.Length >0)
            //   text+="(" +unread.Length.ToString() +")";
            //return text;
        }
    }
}
